package top.kangshuai.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.kangshuai.dao.TbTokenInfoDAO;
import top.kangshuai.entity.TbTokenInfo;
import top.kangshuai.model.UtilModel;
import top.kangshuai.service.UtilService;
import top.kangshuai.utils.ImageCode;
import top.kangshuai.utils.MyUtils;
/**
 * 
 * @author ks187
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UtilServiceImpl implements UtilService {
  @Autowired
  private TbTokenInfoDAO tokenInfoDAO;

  @Override
  public String makeImageCode(UtilModel model) throws Exception {
    String code = ImageCode.makeCode();
    // 获取token信息
    TbTokenInfo tokenInfo = model.getTbTokenInfo();
    // 判断图片效验码是否存在
    TbTokenInfo sInfo = tokenInfoDAO.queryImageCode(tokenInfo);
    if (sInfo == null) {
      // 不存在就将图片code写入
      // 将图片code写入
      tokenInfo.setInfo(code);
      tokenInfoDAO.addImageCode(tokenInfo);
    } else {
      sInfo.setInfo(code);
      tokenInfoDAO.updateImageCode(sInfo);
    }
    return code;

  }
  
  @Override
  public boolean checkImageCode(TbTokenInfo tokenInfo) throws Exception{
    //code不存在就返回错误
    if (MyUtils.isEmpty(tokenInfo.getInfo())) {
      return false;
    }
    TbTokenInfo sInfo=tokenInfoDAO.queryImageCode(tokenInfo);
    if (sInfo==null) {
      //不存在就返回false
      return false;
    }
    //删除数据库中的code（只能使用一次）
    tokenInfoDAO.deleteImageCode(sInfo);
    //返回数据库中code和传入的code比对结果
    return sInfo.getInfo().equalsIgnoreCase(tokenInfo.getInfo());
    
    
  }
}
